package push.tools.service.service.task;


import com.alibaba.fastjson2.JSON;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import push.tools.service.entity.push.PushTaskBean;
import push.tools.service.entity.push.RecordsBean;
import push.tools.service.mapper.task.TaskMapper;
import push.tools.service.utils.TimeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TaskLogService {

    @Autowired
    public SqlSessionFactory sqlSessionFactory;

    public void newTaskLog(String pushId, String creator, String status, String record) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            TaskMapper mapper = session.getMapper(TaskMapper.class);
            PushTaskBean pushTaskBean = new PushTaskBean();
            pushTaskBean.pushId = pushId;
            pushTaskBean.creator = creator;
            pushTaskBean.status = status;
            List<RecordsBean> list = new ArrayList<>();
            RecordsBean bean = new RecordsBean();
            bean.time = TimeUtils.getCurrentTime();
            bean.record = record;
            list.add(bean);
            pushTaskBean.pushRecords = JSON.toJSONString(list);
            mapper.newRecords(pushTaskBean);
        }
    }

    public void addTaskLog(String pushId, String status, String record) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            TaskMapper mapper = session.getMapper(TaskMapper.class);
            Map<String, String> params = new HashMap<>();
            RecordsBean bean = new RecordsBean();
            bean.time = TimeUtils.getCurrentTime();
            bean.record = record;
            String jsonString = JSON.toJSONString(bean);
            params.put("pushId", pushId);
            params.put("record", jsonString);
            params.put("status", status);
            mapper.addRecords(params);
        }
    }

    public List<PushTaskBean> queryLog() {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            TaskMapper mapper = session.getMapper(TaskMapper.class);
            Map<String, String> params = new HashMap<>();
            return mapper.queryAllRecords(params);
        }
    }
}
